package com.pla;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.VideoView;

@Deprecated
public class PhotoActivity extends Activity implements Callback,
		OnClickListener {

	private Camera camera;
	private SurfaceHolder surfaceHolder;
	private static int picCounter = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.i("com.pla", "photoactivity started");

		// setup view
		setContentView(R.layout.photo);

		// fetch elements
		VideoView photoView = (VideoView) findViewById(R.id.VideoView01);
		surfaceHolder = photoView.getHolder();
		surfaceHolder.addCallback(this);

		Button photoBtn = (Button) findViewById(R.id.Button01);
		photoBtn.setOnClickListener(this);
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		camera = Camera.open();
		try {
			camera.setPreviewDisplay(arg0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		camera.startPreview();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		camera.stopPreview();
		camera.release();
		camera = null;
	}

	@Override
	public void onClick(View arg0) {
		Log.i("com.pla", "onClick");
		if (null != camera) {
			camera.takePicture(new ShutterCallback() {

				@Override
				public void onShutter() {
					Log.d("com.pla", "onShutter");
				}
			}, new PictureCallback() {

				@Override
				public void onPictureTaken(byte[] arg0, Camera arg1) {
					// Log.d("com.pla", "onPictureTaken - raw: " + arg0.length);
				}
			}, new PictureCallback() {

				@Override
				public void onPictureTaken(byte[] arg0, Camera arg1) {
					Log.d("com.pla", "onPictureTaken - jpeg: " + arg0.length);
					savePicture(arg0);
				}
			});
		}
	}

	private void savePicture(byte[] picture) {
		Log.d("com.pla", "Saving picture");
		try {
			FileOutputStream openFileOutput = getApplicationContext()
					.openFileOutput(getFilename(), MODE_PRIVATE);
			openFileOutput.write(picture);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getFilename() {
		return "myFile" + (picCounter++) + ".jpg";
	}
}
